< previous page page_367 next page >

Page 367
note.gif The CreateObject function is not necessary to use late binding. You can also write code to use late binding as follows:
    Dim objX As Object
    Set objX = New MyObj.MyClass
 square.gif

One example of when you might want to use late binding is when creating an instance of an object on a remote machine.
Destroying the Object
Assigning Nothing to an object variable frees up resources associated with the object and causes the code in the class module's Terminate to be executed. You accomplish this feat by using a Set statement:
Set objTemp = Nothing
tip.gif
Even though the contents of objects are no longer available when a form or module containing them is destroyed, it is good programming practice to set objects equal to Nothing when you are finished with them. This ensures that all memory resources are freed and the object is destroyed.

Creating Objects from Other Projects
When you are accessing classes in other loaded VB projects or ActiveX DLLs, you can also include the project name:
Dim objX As New MyProject.clsMyClass
Remember, to access classes in other projects or DLLs, you have to add them to the Project References list.
Adding Your Own Events
Visual Basic objects can raise events, such as the Load event of a form. Events provide a way for an object to execute code written by the user of an object. The object triggers the event by way of an event procedure. You have already learned how to place code in event procedures. To create an event in your own class, you need to do two things:
1. Declare the event in the class.
2. Use the RaiseEvent statement to trigger the event when appropriate.
Now you can create a sample event in the employee class. Suppose you want to add a way to return errors to the user of an object. First, declare an event called DataError in the General Declarations section of clsEmployee, by adding a single line of code:
Public Event DataError(ByVal sMessageText As String)
Next, you need to add code to trigger the event. Recall the earlier method CalcRaise, which relies on the Salary property of the object. If the user does not assign a value to Salary property, then a raise cannot be properly calculated. You can modify CalcRaise to send this information to the user via the DataError event by adding a simple If statement:
If Me.Salary = 0 Then RaiseEvent DataError("SALARY UNSPECIFIED!!")

 
< previous page page_367 next page >